package com.yaoweigroup.community.ui.go;

import java.util.ArrayList;
import java.util.List;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.route.RouteSearch;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.LineHistoryAdapter;
import com.yaoweigroup.community.db.DBUtil;
import com.yaoweigroup.community.dialog.RouteSearchPoiDialog;
import com.yaoweigroup.community.dialog.RouteSearchPoiDialog.OnListItemClick;
import com.yaoweigroup.community.enity.HistoryWord;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 公交换乘
 * 
 * @author xi
 * 
 */
public class ChangeLineActivity extends Activity implements OnClickListener,
		OnPoiSearchListener {

	private int busMode = RouteSearch.BusDefault;// 公交默认模式
	private int drivingMode = RouteSearch.DrivingDefault;// 驾车默认模式
	private int walkMode = RouteSearch.WalkDefault;// 步行默认模式
	private ListView listView;
	private RelativeLayout left_rl;
	private LineHistoryAdapter adapter;
	private List<HistoryWord> list;

	private ImageView bus_iv;
	private ImageView car_iv;
	private TextView search_tv;
	private EditText start_et;
	private EditText end_et;
	private TextView history_tv;
	private RelativeLayout history_rl;

	private int routeType = 1;
	private LatLonPoint startPoint = null;
	private LatLonPoint endPoint = null;
	private PoiSearch.Query startSearchQuery;
	private PoiSearch.Query endSearchQuery;

	private String startStr;
	private String endStr;

	private ProgressDialog progDialog;
	private DBUtil dbUtil;

	private ImageView change_iv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change_line);

		dbUtil = DBUtil.newInstance(this);
		history_rl = (RelativeLayout) findViewById(R.id.history_rl);
		history_tv = (TextView) findViewById(R.id.history_tv);
		history_tv.setOnClickListener(this);
		start_et = (EditText) findViewById(R.id.start_et);
		end_et = (EditText) findViewById(R.id.end_et);

		bus_iv = (ImageView) findViewById(R.id.bus_iv);
		bus_iv.setOnClickListener(this);
		car_iv = (ImageView) findViewById(R.id.car_iv);
		car_iv.setOnClickListener(this);
		search_tv = (TextView) findViewById(R.id.search_tv);
		search_tv.setOnClickListener(this);

		list = new ArrayList<HistoryWord>();
		adapter = new LineHistoryAdapter(this, list);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.listView);
		listView.setAdapter(adapter);

		change_iv = (ImageView) findViewById(R.id.change_iv);
		change_iv.setOnClickListener(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				String keyword = list.get(arg2).getKeyword();
				end_et.setText(keyword);
			}
		});
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.car_iv:
			bus_iv.setImageResource(R.drawable.common_topbar_route_bus_normal);
			car_iv.setImageResource(R.drawable.common_topbar_route_car_pressed);
			drivingRoute();
			break;
		case R.id.bus_iv:
			bus_iv.setImageResource(R.drawable.common_topbar_route_bus_pressed);
			car_iv.setImageResource(R.drawable.common_topbar_route_car_normal);
			busRoute();
			break;
		case R.id.search_tv:
			search();
			break;
		case R.id.history_tv:
			try {
				dbUtil.db.deleteAll(HistoryWord.class);
				list.clear();
				adapter.setDataChange(list);
				history_rl.setVisibility(View.GONE);
			} catch (Exception e) {
			}
			break;
		case R.id.change_iv:

			String start = start_et.getText().toString();
			String end = end_et.getText().toString();
			end_et.setText(start);
			start_et.setText(end);
			startPoint = null;
			endPoint = null;
			break;

		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		try {
			List<HistoryWord> historys = dbUtil.db.findAll(HistoryWord.class);
			if (historys != null && historys.size() > 0) {
				history_rl.setVisibility(View.VISIBLE);
				list.addAll(historys);
				adapter.setDataChange(list);
			} else {
				history_rl.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			history_rl.setVisibility(View.GONE);
		}
	}

	private void search() {
		startStr = start_et.getText().toString();
		endStr = end_et.getText().toString();
		if (startStr.length() == 0 || endStr.length() == 0) {
			Toast.makeText(this, "请输入你要搜索的起点或终点!", 500).show();
			return;
		}
		if (startStr.equals(endStr)) {
			Toast.makeText(this, "距离很近 你可以步行!", 500).show();
			return;
		}
		startSearchResult();// 开始搜终点
	}

	/**
	 * 查询路径规划起点
	 */
	public void startSearchResult() {
		if (startPoint != null) {
			endSearchResult();
		} else {
			showProgressDialog();
			startSearchQuery = new PoiSearch.Query(startStr, "", "021"); // 第一个参数表示查询关键字，第二参数表示poi搜索类型，第三个参数表示城市区号或者城市名
			startSearchQuery.setPageNum(0);// 设置查询第几页，第一页从0开始
			startSearchQuery.setPageSize(20);// 设置每页返回多少条数据
			PoiSearch poiSearch = new PoiSearch(this, startSearchQuery);
			poiSearch.setOnPoiSearchListener(this);
			poiSearch.searchPOIAsyn();// 异步poi查询
		}

	}

	/**
	 * 查询路径规划终点
	 */
	public void endSearchResult() {
		if (endPoint != null) {
			searchRouteResult(startPoint, endPoint);
		} else {
			showProgressDialog();
			endSearchQuery = new PoiSearch.Query(endStr, "", "021"); // 第一个参数表示查询关键字，第二参数表示poi搜索类型，第三个参数表示城市区号或者城市名
			endSearchQuery.setPageNum(0);// 设置查询第几页，第一页从0开始
			endSearchQuery.setPageSize(20);// 设置每页返回多少条数据

			PoiSearch poiSearch = new PoiSearch(this, endSearchQuery);
			poiSearch.setOnPoiSearchListener(this);
			poiSearch.searchPOIAsyn(); // 异步poi查询
		}
	}

	/**
	 * 显示进度框
	 */
	private void showProgressDialog() {
		if (progDialog == null)
			progDialog = new ProgressDialog(this);
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("正在搜索");
		progDialog.show();
	}

	/**
	 * 隐藏进度框
	 */
	private void dissmissProgressDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}

	@Override
	public void onPoiItemDetailSearched(PoiItemDetail arg0, int arg1) {

	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {

		dissmissProgressDialog();

		if (rCode == 0) {// 返回成功
			if (result != null && result.getQuery() != null
					&& result.getPois() != null && result.getPois().size() > 0) {// 搜索poi的结果
				if (result.getQuery().equals(startSearchQuery)) {
					List<PoiItem> poiItems = result.getPois();// 取得poiitem数据
					RouteSearchPoiDialog dialog = new RouteSearchPoiDialog(
							ChangeLineActivity.this, poiItems);
					dialog.setTitle("您要找的起点是:");
					dialog.show();
					dialog.setOnListClickListener(new OnListItemClick() {
						@Override
						public void onListItemClick(
								RouteSearchPoiDialog dialog,
								PoiItem startpoiItem) {
							startPoint = startpoiItem.getLatLonPoint();
							startStr = startpoiItem.getTitle();
							start_et.setText(startStr);
							endSearchResult();// 开始搜终点
						}

					});
				} else if (result.getQuery().equals(endSearchQuery)) {
					List<PoiItem> poiItems = result.getPois();// 取得poiitem数据
					RouteSearchPoiDialog dialog = new RouteSearchPoiDialog(
							ChangeLineActivity.this, poiItems);
					dialog.setTitle("您要找的终点是:");
					dialog.show();
					dialog.setOnListClickListener(new OnListItemClick() {
						@Override
						public void onListItemClick(
								RouteSearchPoiDialog dialog, PoiItem endpoiItem) {
							endPoint = endpoiItem.getLatLonPoint();
							endStr = endpoiItem.getTitle();
							end_et.setText(endStr);
							searchRouteResult(startPoint, endPoint);//
							// 进行路径规划搜索
						}

					});
				}
			} else {
				Toast.makeText(this, "没有搜索到结果", 500).show();
			}
		} else if (rCode == 27) {
			Toast.makeText(this, "网络错误", 500).show();

		} else if (rCode == 32) {

			// ToastUtil.show(RouteActivity.this, R.string.error_key);
		} else {
			Toast.makeText(this, "其它错误", 500).show();
		}
	}

	private void searchRouteResult(LatLonPoint start, LatLonPoint end) {

		try {
			HistoryWord word = new HistoryWord();
			word.setKeyword(endStr);
			dbUtil.db.saveOrUpdate(word);
		} catch (Exception e) {

		}

		Intent intent = new Intent(this, RouteActivity.class);
		Bundle bundle = new Bundle();
		bundle.putParcelable("start", start);
		bundle.putParcelable("end", end);
		bundle.putInt("type", routeType);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	/**
	 * 选择公交模式
	 */
	private void busRoute() {
		routeType = 1;// 标识为公交模式
		busMode = RouteSearch.BusDefault;

	}

	/**
	 * 选择驾车模式
	 */
	private void drivingRoute() {
		routeType = 2;// 标识为驾车模式
		drivingMode = RouteSearch.DrivingSaveMoney;
	}
}
